package com.git.hui.yinshua.biz.order.dao.repository;

import com.git.hui.yinshua.api.model.CntDto;
import com.git.hui.yinshua.api.model.constants.GlobalConstants;
import com.git.hui.yinshua.api.model.order.OrderStatusEnum;
import com.git.hui.yinshua.api.model.order.OrderTypeEnum;
import com.git.hui.yinshua.api.model.order.PayStatusEnum;
import com.git.hui.yinshua.biz.order.dao.entity.OrderEntity;
import com.git.hui.yinshua.biz.order.dao.entity.OrderItemEntity;
import com.git.hui.yinshua.biz.order.dao.mapper.OrderMapper;
import com.git.hui.yinshua.biz.rest.models.order.req.OrderCreateReq;
import com.git.hui.yinshua.biz.rest.models.order.req.OrderQueryReq;
import com.git.hui.yinshua.biz.util.ImgUtil;
import com.git.hui.yinshua.biz.util.PriceUtil;
import com.git.hui.yinshua.common.DateUtil;
import com.git.hui.yinshua.common.id.OrderIdGen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author YiHui
 * @date 2024/6/20
 */
@Repository
public class OrderRepository {
    @Autowired
    private OrderMapper orderMapper;


    /**
     * 保存订单
     *
     * @param req
     * @return
     */
    public OrderEntity addOrder(OrderCreateReq req) {
        OrderEntity order = new OrderEntity();
        order.setId(OrderIdGen.genOrderId());
        order.setUid(req.getUserId());
        order.setOrderAmount(PriceUtil.toCentPrice(req.getOrderAmount()));
        order.setOriginalAmount(PriceUtil.toCentPrice(req.getOriginalAmount()));
        order.setShippingAmount(PriceUtil.toCentPrice(req.getShippingAmount()));
        order.setPayAmount(PriceUtil.toCentPrice(req.getPayAmount()));
        order.setOrderTime(new Timestamp(System.currentTimeMillis()));
        order.setOrderStatus(OrderStatusEnum.TO_PAY.getStatus());
        order.setPayStatus(PayStatusEnum.TO_PAY.getStatus());
        order.setReceivingPerson(req.getReceivingPerson());
        order.setReceivingArea(req.getReceivingArea());
        order.setReceivingAddress(req.getReceivingAddress());
        order.setReceivingPhone(req.getReceivingPhone());
        order.setRemark(req.getRemark() == null ? "" : req.getRemark());
        order.setDownloadCnt(0);
        order.setType(req.getType() == null ? OrderTypeEnum.NORMAL.getType() : req.getType());
        orderMapper.saveOrder(order);
        return order;
    }

    /**
     * 保存订单详情
     *
     * @param order
     * @param req
     * @return
     */
    public List<OrderItemEntity> addOrderItems(OrderEntity order, OrderCreateReq req) {
        List<OrderItemEntity> list = new ArrayList<>();
        req.getItemList().forEach(item -> {
            OrderItemEntity entity = new OrderItemEntity();
            entity.setOrderId(order.getId());
            entity.setGoodsId(item.getGoodsId());
            entity.setGoodsName(item.getGoodsName());
            entity.setGoodsIntro(item.getGoodsIntro());
            entity.setGoodsThumb(item.getGoodsThumb());
            entity.setBuyCnt(item.getBuyCnt());
            entity.setGoodsPrice(PriceUtil.toCentPrice(item.getGoodsPrice()));
            entity.setOrderPrice(PriceUtil.toCentPrice(item.getOrderPrice()));
            entity.setOrderQuantity(item.getOrderQuantity());
            entity.setUploadImgs(ImgUtil.toImgs(item.getUploadImgs()));
            entity.setOriginalImgs(ImgUtil.toImgs(item.getOriginalImgs()));
            entity.setSpecId(item.getSpecId());
            entity.setSpec(item.getSpec());
            entity.setRemark(item.getRemark());
            list.add(entity);
        });
        orderMapper.saveOrderItems(list);
        return list;
    }


    public List<OrderEntity> listOrders(OrderQueryReq req) {
        if (CollectionUtils.isEmpty(req.getState())) {
            req.setState(null);
        }
        return orderMapper.listOrder(req);
    }

    public int count(OrderQueryReq req) {
        return orderMapper.count(req);
    }

    public List<CntDto> countByStatus(OrderQueryReq req) {
        return orderMapper.countByStatus(req);
    }

    public OrderEntity queryOrderDetail(Long orderId) {
        return orderMapper.getDetailById(orderId);
    }

    public OrderEntity querySimpleOrderForUpdate(Long orderId) {
        return orderMapper.getSimpleOrderByIdForUpdate(orderId);
    }

    public boolean deleteOrder(Long orderId) {
        return orderMapper.deleteOrder(orderId) > 0;
    }

    /**
     * 更新收货地址
     *
     * @param order
     * @return
     */
    public boolean updateReceiveInfo(OrderEntity order) {
        return orderMapper.updateOrderAddress(order) > 0;
    }

    /**
     * 更新订单上的图片
     *
     * @param detailId
     * @param orgImgs
     * @param cutImgs
     * @return
     */
    public boolean updateOrderDetailImgs(Integer detailId, String orgImgs, String cutImgs) {
        return orderMapper.updateOrderItemImgs(detailId, orgImgs, cutImgs) > 0;
    }

    /**
     * 发货，将订单状态更新为待收货
     *
     * @return
     */
    public boolean updateToReceive(Long orderId, String companyCode, String deliveryCode) {
        return orderMapper.updateToReceive(orderId, companyCode, deliveryCode) > 0;
    }

    /**
     * 更新为待发货
     *
     * @param orderId
     * @return
     */
    public boolean updateToExpress(Long orderId) {
        return orderMapper.updateToExpress(orderId) > 0;
    }


    /**
     * 更行订单状态
     *
     * @param orderId
     * @param status
     * @return
     */
    public boolean updateOrderStatus(Long orderId, Integer status) {
        return orderMapper.updateStatus(orderId, status) > 0;
    }

    /**
     * 订单支付状态变更
     *
     * @param orderId
     * @return
     */
    public boolean updatePayStatus(Long orderId, PayStatusEnum pay, OrderStatusEnum orderStatus, Long paySucceedTime) {
        if (pay == PayStatusEnum.SUCCEED) {
            // 支付成功
            return orderMapper.updatePaySucceed(orderId, orderStatus.getStatus(), paySucceedTime != null ? DateUtil.parse2seconds(paySucceedTime) : null) > 0;
        } else if (pay == PayStatusEnum.FAILED) {
            // 支付失败
            return orderMapper.updatePayStatus(orderId, pay.getStatus()) > 0;
        } else if (pay == PayStatusEnum.PAYING) {
            return orderMapper.updatePayStatus(orderId, pay.getStatus()) > 0;
        } else if (pay == PayStatusEnum.REFUNDING) {
            // 退款场景，更新支付状态
            return orderMapper.updatePayStatus(orderId, pay.getStatus()) > 0;
        } else if (pay == PayStatusEnum.REFUNDED) {
            // 退款成功
            return orderMapper.updateRefundSucceed(orderId) > 0;
        }
        return true;
    }

    public boolean updateDownloadCnt(Long orderId) {
        return orderMapper.updateDownloadCnt(orderId) > 0;
    }

    /**
     * 查询超时未支付的订单
     *
     * @return
     */
    public List<Long> queryOverTimeOrders() {
        Long overTime = System.currentTimeMillis() - GlobalConstants.OrderApi.PAY_INTERVAL_TIME;
        return orderMapper.queryOverTimeOrders(DateUtil.format(DateUtil.DB_FORMAT, overTime));
    }
}
